package com.example.expandablelistview.multimedia;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import com.example.expandablelistview.R;

public class PlayVideo extends Activity implements SurfaceHolder.Callback {
	private SurfaceView mPreView;
	private SurfaceHolder mHolder;
	MediaPlayer mPlayer;
	Button mPlayBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mul_playvideo);
		
		mPreView = (SurfaceView) findViewById(R.id.surface);
		mHolder = mPreView.getHolder();
		mHolder.addCallback(this);
		
		mPlayBtn = (Button) findViewById(R.id.play);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (mPlayer!=null){
			mPlayer.release();
			mPlayer = null;
		}
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.play:
			if (!mPlayer.isPlaying()){
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}else{
				mPlayer.pause();
				mPlayBtn.setText("Play");
			}
			break;
		case R.id.stop:
			mPlayer.stop();
			try {
				mPlayer.prepare();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		}
	}
	
	public void surfaceCreated(SurfaceHolder holder) {
		if (mPlayer == null){
			mPlayer = new MediaPlayer();
		}else{
			mPlayer.reset();
		}
		String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
		try {
			mPlayer.setDataSource(sd + "/testvideo.3gp");
			mPlayer.setDisplay(holder);
			mPlayer.prepare();
			mPlayer.setOnCompletionListener(mComplete);
			mPlayer.setOnVideoSizeChangedListener(mSizeChange);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	OnCompletionListener mComplete = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mp) {
			mPlayBtn.setText("Play");
		}
	};
	
	OnVideoSizeChangedListener mSizeChange = new OnVideoSizeChangedListener() {
		public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
			
		}
	};
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {}
	public void surfaceDestroyed(SurfaceHolder holder) {}

}
